// pages/name/name.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    radioValue: 'GG', // 初始时没有选中的值
    radioLengthChange: 2,
    surname: "",
    nameDescription: "",
    buttonTexts: [
      {
        type: 'primary',
        text: '取消',
        value: 0
      },
      { 
        type: 'default',
        text: '9.9元/3次',
        value: 1,
      }
    ],
    isRecharge:false,
    items: [
      { name: '阳光', selected: false },
      { name: '雅致', selected: false },
      { name: '清新', selected: false },
      { name: '自然', selected: false },
      { name: '时尚', selected: false },
      { name: '朝气', selected: false },
      { name: '艺术', selected: false },
      { name: '家国', selected: false },
      { name: '奔放', selected: false },
      { name: '科技', selected: false },
      { name: '诗意', selected: false },
      { name: '美好', selected: false }
    ]
  },

  inputChange: function (e) {
    let value = e.detail.value
    const inputType = /[^\u4E00-\u9FA5]/g
    this.setData({
      surname: value.replace(inputType, '')
    })
    return value.replace(inputType, '')
  },

  inputDescriptionChange(e) {
    this.setData({
      nameDescription: e.detail.value
    })
  },

  toggleSelect: function (e) {
    const index = e.currentTarget.dataset.index;
    const selected = !this.data.items[index].selected;

    // 更新数据
    this.setData({
      ['items[' + index + '].selected']: selected
    });
  },

  radioChange(e) {
    const value = e.currentTarget.dataset.value;
    console.log("value:" + value);
    this.setData({
      radioValue: value,
    });
  },

  radioLengthChange(e) {
    const value = e.detail.value;
    //console.log("value:" + (Number(value)+Number(1)));
    this.setData({
      radioLengthChange: Number(value) + Number(1),
    });
  },

  radioCheckChange(e) {
    let index = e.currentTarget.dataset.index;
    this.data.items[index].selected = !(this.data.items[index].selected);
    console.log('点击的元素的 index:', this.data.items[index].name);
    var dataList = this.data.items;
    this.setData({
      items: dataList,
    });
  },


  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },

  startPay(e) {
    const { value } = e.detail.item;
    if (value === 0) {
      this.setData({
        isRecharge: false
      });
    } else if (value === 1) {
      this.setData({
        isRecharge: false
      });
    }
  },

  //开始生产名字
  startProductionName () {
    var Bmob = require('../../dist/Bmob-2.5.2.min')
    let aiName = '生成5个';
    if (this.data.surname === undefined || this.data.surname == null || this.data.surname == "" || this.data.surname.length == 0) {
      wx.showToast({
        title: '请输入宝贝姓氏',
        icon: 'error',
      })
      return;
    }

    aiName += "姓" + this.data.surname + "的名字。名字要求:必须以"+ this.data.surname+"," + this.data.nameDescription+"，"

    if (this.data.radioValue == "GG") {
      aiName += "一定是"+ this.data.radioLengthChange + "个字长的男生名字，并解释名字含义(meaning),显示名字拼音(pinyin)"
      console.log("GG")
    } else {
      aiName +="一定是"+ this.data.radioLengthChange + "个字长的女生名字，并解释名字含义(meaning),显示名字拼音(pinyin)"
      console.log("MM")
    }

    let nameStyle = "   名字风格："
    for (var i = 0; i < this.data.items.length; i++) {
      if (this.data.items[i].selected) {
        nameStyle += this.data.items[i].name + "，"
      }
    }
    aiName = aiName + nameStyle+"  返回结果必须是JSON数组,不需要带上```json,其中name代表名字全称,meaning代表名字含义,pinyin代表名字的拼音,返回的JSON数组只需要包括,name,meaning,pinyin三个变量,"

    console.log("ainame = " + aiName)
    let chatAi = Bmob.ChatAI()
    let data = {
      "messages": [{
        "content": aiName,
        "role": "user"
      }],
      "model":"gpt-3.5-turbo",
      "session": "b1"
    }
    console.log("JSON = " + JSON.stringify(data))
    setTimeout(function () {
      console.log(this.connect,"this connect");
      chatAi.send(JSON.stringify(data))
   }, 2000);

    let msg = ""

    chatAi.onClose((c) => {
      console.log("连接被关闭");
      //重新连接
      chatAi.connect()
    })

    wx.showLoading({
      title: 'ai生成中...', // 加载提示框的标题
      mask: true // 是否显示透明蒙层，防止触摸穿透，默认为false
    });

    chatAi.onMessage((res) => {
      if (res == "done" && msg.length > 0) {
        wx.hideLoading(); // 关闭加载框
        msg = msg.replace("param1:","");
        msg = msg.replace("```json", "");
        msg = msg.replace("```", "");
        console.log('../result/result?result='+msg);
        wx.navigateTo({
          url: '../result/result?result='+msg
        })
      } else if(res!="done"){
        msg = msg + res   
      }
    })
    chatAi.onError((c) => {
      console.log("连接错误");
      wx.hideLoading(); // 关闭加载框
      wx.showToast({
        title: '服务器异常',
        icon: 'error',
      })
    })
  },

  requestDataFromServer: function () {
    // var Bmob = require('../../dist/Bmob-2.5.2.min')
    // var openid = wx.getStorageSync('openid');
    // const query = Bmob.Query("Count");
    // query.equalTo("openid", "==", openid);
    // query.find().then(res => {
    //   if (Array.isArray(res)) {
    //     var count = Bmob.Query('Count');
    //     if(res.length == 0){
    //       count.set("openid",openid);
    //       count.set("count", 2);
    //       count.save().then(res => {
    //         this.startProductionName() 
    //       })
    //     }else{
    //       var item = res[0]
    //       var countNumber = item.count;
    //       if(countNumber==0){
    //         this.setData({
    //           isRecharge: true,
    //         });
    //         return;
    //       }
    //       countNumber = countNumber - 1;

    //       count.set('id', item.objectId) //需要修改的objectId
    //       count.set("count", countNumber)
    //       count.save().then(res => {
    //         console.log(res)
    //         }).catch(err => {
    //         console.log(err)
    //         })
    //       //开始ai 生成名字
    //       this.startProductionName() 
    //     } 
    //   }
    // });    
      //开始ai 生成名字
      this.startProductionName() 
  },

  onShareAppMessage: function (res) {
    return {
      title: 'AI起名专家',
      path: '/pages/main/main.wxml'
    }
  }
})